package com.ibeetl.cms.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.HttpRequestLocal;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.EssentialInformation;
import com.ibeetl.cms.entity.TelentCard;
import com.ibeetl.cms.service.EssentialInformationService;
import com.ibeetl.cms.service.TelentCardService;
import com.ibeetl.cms.web.query.EssentialInformationQuery;
import com.ibeetl.cms.web.query.TelentCardQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * EssentialInformation 接口
 */
@Controller
public class EssentialInformationController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/essentialInformation";


    @Autowired private EssentialInformationService essentialInformationService;

    @Autowired
    CorePlatformService platformService;
    @Autowired
    FileService fileService;

    @Autowired private TelentCardService telentCardService;

    @Autowired
    HttpRequestLocal httpRequestLocal;

    @Autowired
    CoreUserService userService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("essentialInformation.person")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/essentialInformation/index.html") ;
        view.addObject("search", EssentialInformationQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("essentialInformation.person")
    @ResponseBody
    public ModelAndView edit() {
        ModelAndView view = new ModelAndView("/cms/essentialInformation/edit.html");

        CoreUser user = platformService.getCurrentUser();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(user.getId());

        //人才卡
        TelentCardQuery condition = new TelentCardQuery();
        condition.setUserid(user.getId().intValue());
            PageQuery page = condition.getPageQuery();
        PageQuery<TelentCard> pageQuery = telentCardService.queryByCondition(page);
        List<TelentCard> telentCards = pageQuery.getList();

        TelentCard telentCard = new TelentCard();
        if(telentCards.size() > 0){
            telentCard = telentCards.get(0);
        }

        view.addObject("telentCard", telentCard);

        view.addObject("essentialInformation", essentialInformation);
        return view;
    }

    @GetMapping(MODEL + "/initEdit.do")
    @Function("essentialInformation.person")
    @ResponseBody
    public ModelAndView initEdit() {
        ModelAndView view = new ModelAndView("/cms/essentialInformation/edit.html");

        CoreUser user = platformService.getCurrentUser();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(user.getId());
        view.addObject("essentialInformation", essentialInformation);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("essentialInformation.person")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/essentialInformation/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("essentialInformation.person")
    @ResponseBody
    public JsonResult<PageQuery> list(EssentialInformationQuery condtion)
    {
        CoreUser user = platformService.getCurrentUser();
        long userId = user.getId();
        condtion.setUserId((int) userId);
        PageQuery page = condtion.getPageQuery();
        essentialInformationService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("essentialInformation.person")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)EssentialInformation essentialInformation)
    {
        essentialInformationService.save(essentialInformation);
        return JsonResult.success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function("essentialInformation.person")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  EssentialInformation essentialInformation) {
       CoreUser initUser = platformService.getCurrentUser();
       if("1".equals(initUser.getNeedInfo())){
           initUser.setNeedInfo("2");
       }else {
           initUser.setNeedInfo("0");
       }
       userService.update(initUser);

        boolean success = essentialInformationService.update(essentialInformation);
        String arr1[]={"industrial_talents","preparatory_talent","buy_house_subsidies","skill"
        ,"professional_technology","renting","doctoral_subsidy","outbound_subsidy","highlevel_talents",
        "quit","entry","key_information","medical_care"};
        if (success) {
            userService.updateUserName(essentialInformation.getUserId(),essentialInformation.getName());//修改登录名
            CoreUser user=userService.getUserById(essentialInformation.getUserId().longValue());
            httpRequestLocal.setSessionValue(CorePlatformService.ACCESS_CURRENT_USER,user);//把修改的信息缓存
            CoreUser currentUser = platformService.getCurrentUser();
            essentialInformation.setAccountOpeningBank(essentialInformation.getBankTypeName()+essentialInformation.getAccountOpeningBank()+"支行");
            for (int i=0;i<arr1.length;i++) {
                essentialInformationService.ToUpdateReported(essentialInformation.getName(),
                        essentialInformation.getSex(), essentialInformation.getBirthday(), essentialInformation.getNation()
                        , essentialInformation.getPoliticalOutlook(), essentialInformation.getMaritalStatus(),
                        essentialInformation.getNativePlace(), essentialInformation.getMailBox(), essentialInformation.getContactNumber(),
                        essentialInformation.getPhoneNumber(), essentialInformation.getIdType(), essentialInformation.getIdentificationNumber(),
                        essentialInformation.getAccountOpeningBank(), essentialInformation.getBankCardNumber(),
                        essentialInformation.getGraduateSchool(), essentialInformation.getMajor(), essentialInformation.getEducation(),
                        essentialInformation.getAcademicDegree(), essentialInformation.getCurrentWorkingEnterprise(),
                        essentialInformation.getPosition(), essentialInformation.getMajorAchievements(), arr1[i],currentUser.getId().intValue());
            }
                    return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    @PostMapping(MODEL + "/initEdit.json")
    @Function("essentialInformation.person")
    @ResponseBody
    public JsonResult<String> initEdit(@Validated(ValidateConfig.UPDATE.class)  EssentialInformation essentialInformation) {
        CoreUser user = platformService.getCurrentUser();
        //初次登录填写完基本信息 状态2
        user.setNeedInfo("2");
        userService.update(user);
        user.setName(essentialInformation.getName());
        boolean success = essentialInformationService.updateTemplate(essentialInformation);
        if (success) {
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("essentialInformation.person")
    @ResponseBody
    public JsonResult<EssentialInformation>queryInfo(Integer id) {
        EssentialInformation essentialInformation = essentialInformationService.queryById( id);
        return  JsonResult.success(essentialInformation);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("essentialInformation.person")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        essentialInformationService.batchDelEssentialInformation(idList);
        return JsonResult.success();
    }


}
